<!-- components/PaginatedGrid.vue -->
<template>
  <ResponsiveGrid
    ref="gridRef"
    v-bind="gridProps"
  >
    <template #default="{ itemsPerRow, containerWidth }">
      <!-- 内容区域 -->
      <div
        v-for="item in currentPageItems"
        :key="getItemKey(item)"
        class="grid-item"
        :style="itemStyle"
      >
        <slot 
          name="item"
          :item="item"
          :index="getItemIndex(item)"
          :items-per-row="itemsPerRow"
          :container-width="containerWidth"
        />
      </div>
    </template>
  </ResponsiveGrid>

  <!-- 分页控件 -->
  <div v-if="showPagination" class="pagination-container">
    <button 
      :disabled="currentPage === 1"
      @click="goToPage(currentPage - 1)"
    >
      上一页
    </button>
    
    <span class="page-info">
      第 {{ currentPage }} 页 / 共 {{ totalPages }} 页
    </span>
    
    <button 
      :disabled="currentPage === totalPages"
      @click="goToPage(currentPage + 1)"
    >
      下一页
    </button>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, type PropType } from 'vue'
import ResponsiveGrid from './ResponsiveGrid.vue'
import { usePaginationSize } from '../utils/gridLayout'

interface Props {
  items: any[] // 数据列表
  minItemWidth: number
  gap?: number
  containerPadding?: number
  defaultPerRow?: number
  rowsPerPage?: number
  showPagination?: boolean
  getItemKey?: (item: any) => string | number
}

const props = withDefaults(defineProps<Props>(), {
  items: () => [],
  gap: 8,
  containerPadding: 0,
  defaultPerRow: 1,
  rowsPerPage: 3,
  showPagination: true,
  getItemKey: (item: any) => item.id || item.key
})

const emit = defineEmits<{
  'page-change': [page: number, pageSize: number]
  'page-size-change': [pageSize: number]
}>()

const gridRef = ref<InstanceType<typeof ResponsiveGrid> | null>(null)
const currentPage = ref(1)

// 获取每行元素数量
const itemsPerRow = computed(() => {
  return gridRef.value?.itemsPerRow || props.defaultPerRow
})

// 计算分页大小（每页显示的数量）
const pageSize = usePaginationSize(itemsPerRow, props.rowsPerPage)

// 计算总页数
const totalPages = computed(() => {
  if (props.items.length === 0) return 1
  return Math.ceil(props.items.length / pageSize.value)
})

// 获取当前页的数据
const currentPageItems = computed(() => {
  const startIndex = (currentPage.value - 1) * pageSize.value
  const endIndex = startIndex + pageSize.value
  return props.items.slice(startIndex, endIndex)
})

const itemStyle = computed(() => ({
  minWidth: `${props.minItemWidth}px`
}))

const gridProps = computed(() => ({
  minItemWidth: props.minItemWidth,
  gap: props.gap,
  containerPadding: props.containerPadding,
  defaultPerRow: props.defaultPerRow,
  rowsPerPage: props.rowsPerPage
}))

// 监听分页大小变化
watch(pageSize, (newSize) => {
  emit('page-size-change', newSize)
  // 分页大小变化时，重置到第一页
  if (currentPage.value !== 1) {
    currentPage.value = 1
  } else {
    emit('page-change', 1, newSize)
  }
})

// 监听数据变化，如果当前页没有数据，则跳转到最后一页
watch(() => props.items.length, (newLength) => {
  if (currentPage.value > totalPages.value) {
    currentPage.value = Math.max(1, totalPages.value)
  }
})

const goToPage = (page: number) => {
  if (page < 1 || page > totalPages.value) return
  
  currentPage.value = page
  emit('page-change', page, pageSize.value)
}

const getItemIndex = (item: any) => {
  return props.items.indexOf(item)
}

// 暴露给父组件的方法
defineExpose({
  itemsPerRow,
  pageSize,
  currentPage,
  totalPages,
  goToPage,
  updateLayout: () => gridRef.value?.updateLayout()
})
</script>

<style scoped>
.grid-item {
  box-sizing: border-box;
}

.pagination-container {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 16px;
  margin-top: 20px;
  padding: 16px;
}

.pagination-container button {
  padding: 8px 16px;
  border: 1px solid #ddd;
  background: white;
  border-radius: 4px;
  cursor: pointer;
}

.pagination-container button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.page-info {
  color: #666;
  font-size: 14px;
}
</style>